package com.qf.rbac2202.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qf.rbac2202.annotation.DataFilter;
import com.qf.rbac2202.sys.entity.SysDept;
import com.qf.rbac2202.sys.entity.SysUser;
import com.qf.rbac2202.sys.mapper.SysUserMapper;
import com.qf.rbac2202.sys.service.ISysDeptService;
import com.qf.rbac2202.sys.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qf.rbac2202.utils.Constants;
import com.qf.rbac2202.utils.PageQueryUtil;
import com.qf.rbac2202.utils.PageVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author dong_
 * @since 2022-10-28
 */
@Service
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    ISysDeptService deptService;

    @DataFilter
    @Transactional(propagation = Propagation.SUPPORTS)
    @Override
    public PageVo<SysUser> queryUserByPage(Map<String, String> params) {

        final String username = params.get("username");  // 页面输入的用户名查询条件

        // 利用分页工具类，创建分页对象
        final Page<SysUser> sysUserPage = PageQueryUtil.getPage(params);

        // 从params获取数据权限的sql片段
        final String sql = params.get(Constants.DATA_FILETER);

        // 设置查询条件
        final QueryWrapper<SysUser> queryWrapper = new QueryWrapper<SysUser>()
                .eq("status", 1)
                .eq(StringUtils.isNotBlank(username), "username", username)
                .apply(StringUtils.isNotBlank(sql),sql);
//                .in("dept_id","1","2","3");


        this.page(sysUserPage, queryWrapper);

        // 把所有user对象中的 deptName 进行赋值
        final List<SysDept> deptList = deptService.list();

        //  List<SysDept>  --->  Map<部门id,部门名称>
        final HashMap<Long, String> deptMap = new HashMap<>();

        deptList.forEach(sysDept -> deptMap.put(sysDept.getDeptId(), sysDept.getName()));

        // 遍历 sysUserPage 进行部门名称的赋值操作
        sysUserPage.getRecords().forEach(sysUser -> sysUser.setDeptName(deptMap.get(sysUser.getDeptId())));

        // sysUserPage ---> pageVo
        return new PageVo<SysUser>(sysUserPage);

    }
}
